package com.mskj.zxmy.controller;


import com.github.pagehelper.PageInfo;
import com.mskj.zxmy.common.Result;
import com.mskj.zxmy.dto.*;
import com.mskj.zxmy.entity.StockIn;
import com.mskj.zxmy.entity.Ck03Listing;
import com.mskj.zxmy.mapper.StockInMapper;
import com.mskj.zxmy.service.Ck03ListingService;
import com.mskj.zxmy.service.Gy02ProductRepositoryService;
import com.mskj.zxmy.service.StockInService;
import com.mskj.zxmy.service.SupplierService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.constraints.NotBlank;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;


import java.util.Map;


@RestController
@RequestMapping("/api/stock/in")
@Tag(name = "入库接口")
@CrossOrigin
public class StockInController {

    @Autowired
    private StockInService stockInService;
    @Autowired
    private SupplierService supplierService;
    @Autowired
    private Gy02ProductRepositoryService gy02ProductRepositoryService;

    @Autowired
    private Ck03ListingService ck03ListingService;
    @Autowired
    private StockInMapper stockInMapper;

    /**
     * 创建入库单
     *
     * @return 操作结果，包含入库单ID
     */

    @PostMapping("/createIn")
    @Operation(summary = "创建入库单（废）")
    public Result<Map<String, StockIn>> createStockIn() {
        return Result.success(stockInService.createStockIn());
    }

    /**
     * 查询供应商列表
     *
     * @return
     */
    @PostMapping("/getGYS")
    @Operation(summary = "供应商列表（废）")
    public Result getAssociatedSuppliers() {
        return Result.success(supplierService.getAllSuppliers());
    }

    /**
     * 根据任务ID查询工单，并用工单的productName作为id查询产品详情
     *
     * @param id 任务ID
     * @return 产品详情（process, productNumber, productName, typeOfProduct, environmentalProtectionLevel等）
     */
    @PostMapping("/getProductDetailByMissionStream")
    @Operation(summary = "任务工单id查询产品详情")
    public Result<ProductDetailDTO> getProductDetailByMissionStream(@Parameter(description = "任务工单ID") @RequestParam String id) {
        if (id == null || id.isEmpty()) {
            return Result.failed("任务ID不能为空");
        }
        ProductDetailDTO dto = gy02ProductRepositoryService.getProductDetailByMissionStream(id);
        if (dto == null) {
            return Result.failed("未找到对应工单或产品信息");
        }
//    根据工单id查询任务数量
        dto.setNumber(stockInMapper.getNumber(id));
        return Result.success(dto);
    }


    /**
     * 保存入库单及明细
     */
    @PostMapping("/saveStockInWithDetails")
    @Operation(summary = "保存入库单及明细")
    @CrossOrigin
    public Result<StockInSaveDTO> saveStockInWithDetails(@RequestBody StockInSaveDTO dto) {
        boolean success = stockInService.saveStockInWithDetails(dto);
        return success ? Result.success("保存成功") : Result.failed("保存失败");
    }

    /**
     * 保存入库明细信息,修改入库明细入库数量和入库状态
     *
     * @param detail 入库明细地保存数据传输对象，包含需要保存的明细信息
     * @return 返回保存操作的结果，成功或失败
     */
    @PostMapping("/saveDetail")
    @Operation(summary = "保存入库明细修和数量和扫码状态")
    public Result<?> saveDetail(@RequestBody StockInDetailSaveDTO detail) {
        // 调用服务层方法保存入库明细
        //    boolean success = stockInService.saveDetail(detail);
        boolean success = stockInService.updateByDetailId(detail);
        // 根据保存结果返回相应的结果对象
        return success ? Result.success("保存成功") : Result.failed("保存失败");
    }


    /**
     * 筛选入库列表（分页）
     */
    /**
     * 筛选入库列表（分页）
     */
    @GetMapping("/searchStockIn")
    @Operation(summary = "筛选入库单列表（分页）", description = "支持多条件筛选入库单，包含物料信息筛选")
    public Result<PageInfo<Ck03Listing>> searchStockIn(
            @Parameter(description = "入库单号", example = "RK202504130001")
            @RequestParam(required = false) String repositoryNumber,
            @Parameter(description = "物料名称", example = "橡木")
            @RequestParam(required = false) String productName,
            @Parameter(description = "规格", example = "18.0复贴")
            @RequestParam(required = false) String productSpecifications,
            @Parameter(description = "物料类别", example = "科技木皮", schema = @Schema(allowableValues = {"科技木皮", "实木", "人造板", "其他"}))
            @RequestParam(required = false) String materialCategory,
            @Parameter(description = "品牌", example = "福州佳信欧派", schema = @Schema(allowableValues = {"福州佳信欧派", "千年花", "其他品牌"}))
            @RequestParam(required = false) String brand,
            @Parameter(description = "入库状态", example = "未入库", schema = @Schema(allowableValues = {"未入库", "已入库", "部分入库"}))
            @RequestParam(required = false) String repositoryStatus,
            @Parameter(description = "开始日期", example = "2025-04-01")
            @RequestParam(required = false) String startDate,
            @Parameter(description = "结束日期", example = "2025-04-30")
            @RequestParam(required = false) String endDate,
            @Parameter(description = "当前页码", example = "1")
            @RequestParam(required = false, defaultValue = "1") Integer pageNum,
            @Parameter(description = "每页条数", example = "10")
            @RequestParam(required = false, defaultValue = "10") Integer pageSize) {
        Ck03ListingQuery query = Ck03ListingQuery.builder().repositoryNumber(repositoryNumber).productName(productName)                    // 新增：物料名称
                .productSpecifications(productSpecifications) // 新增：规格
                .materialCategory(materialCategory)          // 新增：物料类别
                .brand(brand)                                // 新增：品牌
                .repositoryStatus(repositoryStatus)
                .startDate(startDate)
                .endDate(endDate)
                .pageNum(pageNum)
                .pageSize(pageSize)
                .build();
        return Result.success(ck03ListingService.searchCk03ListingsWithPage(query));
    }


    @PostMapping("/realTimeStockWithPage")
    @Operation(summary = "实时库存分页查询")
    public Result<PageInfo<RealTimeStockDTO>> getRealTimeStockWithPage(@RequestBody RealTimeStockQueryDTO query) {
        return Result.success(stockInService.getRealTimeStockWithPage(query));
    }

    /*
     * 多条件实时库存查询接口
     */
//    @GetMapping("/realTimeStockByCondition")
//    @Operation(summary = "多条件实时库存查询")
//    public Result<List<RealTimeStockDTO>> getRealTimeStockByCondition(
//            @RequestParam(required = false) String productNumber,
//            @RequestParam(required = false) String productModel,
//            @RequestParam(required = false) String productName) {
//        return Result.success(stockInService.getRealTimeStockByCondition(productNumber, productModel, productName));
//    }


    //------------------------------------------------- 2.0--------------------------------------------- //


    /**
     * 查询生产入库单列表（分页）
     *
     * @return
     */
    @PostMapping("/selectAllStockIn")
    @Operation(summary = "查询生产入库列表（分页）")
    public Result<PageInfo<Ck03Listing>> selectAllStockIn(@RequestBody StockInListQueryDTO query) {
        PageInfo<Ck03Listing> result = stockInService.selectAllStockInWithPage(query);
        return Result.success(result);
    }

    /**
     * 修改入库单的入库状态和入库明细的入库数量
     *
     * @param dto
     * @return
     */
    @PostMapping("/confirmStockInDetail")
    @Operation(summary = "确认入库")
    public Result<?> confirmStockInDetail(@RequestBody StockInSaveDTO dto) {
        try {
            boolean success = stockInService.confirmStockInDetail(dto);
            return success ? Result.success("确认入库成功") : Result.failed("确认入库失败");
        } catch (RuntimeException e) {
            return Result.failed(e.getMessage());
        }
    }

    /**
     * 入库明细列表（分页）
     *
     * @param repositoryStatus
     * @param pageNum
     * @param pageSize
     * @return
     */
    @GetMapping("/stockInDetails")
    @Operation(summary = "入库明细列表（分页）")
    public Result<PageInfo<StockInDetailSaveDTO>> getStockInDetails(@RequestParam String repositoryStatus, @RequestParam(defaultValue = "1") Integer pageNum, @RequestParam(defaultValue = "10") Integer pageSize) {
        StockInDetailListQueryDTO query = new StockInDetailListQueryDTO();
        query.setRepositoryStatus(repositoryStatus);
        query.setPageNum(pageNum);
        query.setPageSize(pageSize);
        PageInfo<StockInDetailSaveDTO> result = stockInService.getStockInDetailsWithPage(query);
        return Result.success(result);
    }

    /**
     * 根据入库明细id查询入库明细
     *
     * @param detailId
     * @return
     */
    @GetMapping("/stockInDetail/{detailId}")
    @Operation(summary = "根据入库明细id查询入库明细（含主表和产品信息）")
    public Result<StockInDetailSaveDTO> getStockInDetailById(@PathVariable Integer detailId) {
        StockInDetailSaveDTO detail = stockInService.getStockInDetailById(detailId);
        return detail != null ? Result.success(detail) : Result.failed("未找到该入库明细");
    }


    /**
     * 入库明细多条件分页筛选
     *
     * @param query
     * @return
     */
    @PostMapping("/stockIn/filter")
    @Operation(summary = "入库明细多条件分页筛选")
    public Result<PageInfo<StockInDetailSaveDTO>> filterStockIn(@RequestBody StockInQueryDTO query) {
        PageInfo<StockInDetailSaveDTO> list = stockInService.filterStockInWithPage(query);
        return Result.success(list);
    }


    /**
     * /**
     * 根据入库单查询入库计划
     *
     * @param repositoryNumber
     * @return
     */
    @GetMapping("/selectStockInByRepositoryNumber/{repositoryNumber}")
    @Operation(summary = "根据入库单查询入库计划")
    public Result<StockIn> selectStockInByNumber(@PathVariable @NotBlank(message = "仓库编号不能为空") String repositoryNumber) {
        try {
            StockIn result = stockInService.selectStockInByNumber(repositoryNumber);
            if (result == null) {
                return Result.error(404, "未查询到对应的入库计划");
            }
            return Result.success(result);
        } catch (Exception e) {
            // 可根据具体异常类型做更细粒度处理
            return Result.error(404, "查询入库计划失败：" + e.getMessage());
        }
    }

    /**
     * 根据条码Id查明细及物品信息
     *
     * @param batchBarCodeId
     * @return
     */
    @GetMapping("/getStockInDetailWithProductInfo/{batchBarCodeId}")
    @Operation(summary = "根据条码Id查明细及物品信息")
    public Result<ProductDetailDTO> getStockInDetailWithProductInfo(@PathVariable Integer batchBarCodeId) {
        ProductDetailDTO dto = stockInService.getStockInDetailWithProductInfo(batchBarCodeId);
        return dto != null ? Result.success(dto) : Result.failed("未找到数据");
    }

}


